package com.chen.cloud.micro.consumer.movie.controller;


import com.chen.cloud.micro.consumer.movie.dto.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author ChenTian
 * @date 2022/6/1
 */
@RestController
@RequestMapping("/movie/v1")
public class MovieController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private LoadBalancerClient loadBalancerClient;

    @HystrixCommand(fallbackMethod = "findByIdFallback")
//    @HystrixCommand(fallbackMethod = "findByIdFallback", commandProperties = {
//            @HystrixProperty(name = "execution.isolation.strategy", value = "SEMAPHORE")
//    })
//    @HystrixCommand(fallbackMethod = "findByIdFallback", commandProperties = {
//            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000"),
//            @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
//    }, threadPoolProperties = {
//            @HystrixProperty(name = "coreSize", value = "1"),
//            @HystrixProperty(name = "maxQueueSize", value = "10")
//    })
    @GetMapping("/{id}")
    public User findById(@PathVariable Long id){
        User entity = restTemplate.getForObject("http://micro-provider-user/user/v1/"+id, User.class);
        return entity;
    }

    public User findByIdFallback(Long id, Throwable throwable){
        logger.error("error:",throwable);
        User user = new User();
        user.setId(-1L);
        user.setName("默认用户");
        return user;
    }

    @GetMapping("/log-instance")
    public void logUserInstance(){
        ServiceInstance serviceInstance = loadBalancerClient.choose("micro-provider-user");
        logger.info("{}:{}:{}", serviceInstance.getServiceId(), serviceInstance.getHost(), serviceInstance.getPort());
    }
}
